package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.FirstAdapter;
import com.digitalchina.lxnsy.adapter.SecondAdapter;
import com.digitalchina.lxnsy.api.BusinessCart;
import com.digitalchina.lxnsy.api.BusinessDataMall;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.DataMallVO;
import com.digitalchina.lxnsy.entity.ProductTypeVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.DataMallHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/12/28 17:43
 * 修改备注：
 * ================================================
 */

public class DataMallListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.data_mall_iv_menu)
    ImageView dataMallIvMenu; // 侧滑菜单按钮
    @Bind(R.id.data_mall_tv_search)
    TextView dataMallTvSearch; // 搜索按钮

    public static final int REQUEST_CODE_DATA_LIST = 10000;
    @Bind(R.id.data_mall_drawer_layout)
    DrawerLayout dataMallDrawerLayout;
    @Bind(R.id.listViewFirst)
    ListView listViewFirst;
    @Bind(R.id.listViewSecond)
    ListView listViewSecond;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private String keyWord = "";
    private String code = "";

    private List<DataMallVO> dataMallVOList = new ArrayList<>();

    private FirstAdapter firstAdapter;
    private SecondAdapter secondAdapter;
    private List<ProductTypeVO> productTypeVOList = new ArrayList<>();
    private List<List<ProductTypeVO.SubProductTypesBean>> listList = new ArrayList<>(); // 二级菜单

    @Override
    public void setLayout() {
        setTitle("数据商城");
        setContentLayout(R.layout.activity_data_mall_list);
    }

    @Override
    public void initMember() {

        initRecyclerView();

        // 获取所有类型
        BusinessDataMall.dataMartList(this, "", mHandler);
    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new DataMallHolder(parent);
            }
        });

        onRefresh();
    }


    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                DataMallVO dataMallVO = (DataMallVO) adapter.getAllData().get(position);
                if (dataMallVO.getId() != null)
                    GotoUtil.gotoActivity(DataMallListActivity.this, DataDetailActivity.class, "productId", dataMallVO.getId());
            }
        });
        adapter.setOnItemLongClickListener(new RecyclerArrayAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(int position) {
                DataMallVO dataMallVO = (DataMallVO) adapter.getAllData().get(position);
                if (dataMallVO != null) {
                    BusinessCart.addShoppingCartItem(DataMallListActivity.this, dataMallVO.getId(), "1", dataMallVO.getAmount_num(),
                            dataMallVO.getIntroduce(), dataMallVO.getMerchant().getUserAccId(),
                            dataMallVO.getMerchant().getMerchantName(), dataMallVO.getMerchant().getHeadPortrait(),
                            dataMallVO.getMerchant().getMobilePhone(), dataMallVO.getMerchant().getFullAddress(), mHandler);
                }
                return true;
            }
        });

        listViewFirst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateListView(position);
            }
        });

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_DATA_MART_LIST_CONTENT_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_DATA_MART_LIST_CONTENT_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_ADD_SHOPPING_CART_ITEM_SUCCESS:
                        showToast("已加入购物车");
                        break;
                    case MSG.MSG_ADD_SHOPPING_CART_ITEM_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_DATA_MART_LIST_SUCCESS: // 商品类型 <侧边栏>
                        setLeftView(msg.obj.toString());
                        break;
                    case MSG.MSG_DATA_MART_LIST_FIELD:
                        break;
                }
            }
        };
    }

    /**
     * 设置左侧类型
     */
    private void setLeftView(String json) {
        productTypeVOList = FastJsonUtil.getListBean(json, "body", "productTypeList", ProductTypeVO.class);

        for (int i = 0; i < productTypeVOList.size(); i++) {
            listList.add(productTypeVOList.get(i).getSubProductTypes());
        }
        firstAdapter = new FirstAdapter(this, productTypeVOList);

        firstAdapter.setSelectPosition(0);
        listViewFirst.setAdapter(firstAdapter);
        initSecondListView(0);
    }

    private void initSecondListView(int position) {
        if (listList.size() <= 0)
            return;
        secondAdapter = new SecondAdapter(this, listList.get(position));
        secondAdapter.setSelectPosition(position);
        listViewSecond.setAdapter(secondAdapter);

        listViewSecond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateListView2(position, true);
            }
        });

    }


    private void updateListView(int position) {
        firstAdapter.setSelectPosition(position);
        firstAdapter.notifyDataSetChanged();

        //更新第二ListView
        secondAdapter.setDatas(listList.get(position));
        updateListView2(0, false);
    }

    private void updateListView2(int position, boolean b) {
        secondAdapter.setSelectPosition(position);
        secondAdapter.notifyDataSetChanged();
        if (b) {
            clearSearchContent();
            dataMallDrawerLayout.closeDrawer(GravityCompat.START);
            code = secondAdapter.getCurrentPositionItem().getCode();
            onRefresh();
        }
    }

    /**
     * 清除搜
     */
    private void clearSearchContent() {
        keyWord = "";
        dataMallTvSearch.setText("");
    }

    @Override
    public void callBack(Object object) {
        dataMallVOList = FastJsonUtil.getListBean(object.toString(), "body", "commodityList", DataMallVO.class);
        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (dataMallVOList != null) {
            if (dataMallVOList.size() < limit) {
                adapter.stopMore();
            }
        }

        adapter.addAll(dataMallVOList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onRefresh() {
        page = 1;
        keyWord = "";
        dataMallTvSearch.setText(keyWord);
        BusinessDataMall.datamartlistcontent(this, String.valueOf(page), String.valueOf(limit), keyWord, code, mHandler);
    }

    @Override
    public void onLoadMore() {
            page++;
            BusinessDataMall.datamartlistcontent(this, String.valueOf(page), String.valueOf(limit), keyWord, code, mHandler);
    }

    @OnClick({R.id.data_mall_iv_menu, R.id.data_mall_tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.data_mall_iv_menu:
                dataMallDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.data_mall_tv_search:
                GotoUtil.gotoForResultActivity(this, DataSearchActivity.class, REQUEST_CODE_DATA_LIST);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == DataSearchActivity.RESULT_CODE_DATA_SEARCH) {
            if (null != data && requestCode == REQUEST_CODE_DATA_LIST) {
                //搜索返回数据
                if (null != keyWord || !"".equals(keyWord))
                    keyWord = "";
                if (null != adapter || adapter.getAllData().size() > 0) {
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                }
                keyWord = data.getStringExtra("KeyWord");

                searchData(keyWord);
            }
        }
    }

    /**
     * 根据关键字 搜索
     *
     * @param keyWord
     */
    private void searchData(String keyWord) {
        dataMallTvSearch.setText(keyWord);
        code = ""; // 搜索的时候制空分类筛选关键字
        page = 1;
        BusinessDataMall.datamartlistcontent(this, String.valueOf(page), String.valueOf(limit), keyWord, "", mHandler);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
